// 博客语言切换组件
class BlogLanguageSwitcher extends HTMLElement {
    constructor() {
        super();
        this.currentLanguage = 'zh-CN';
        this.availableLanguages = [
            { code: 'zh-CN', name: '简体中文', flag: '🇨🇳' },
            { code: 'en-US', name: 'English', flag: '🇺🇸' },
            { code: 'ja-JP', name: '日本語', flag: '🇯🇵' },
            { code: 'ko-KR', name: '한국어', flag: '🇰🇷' }
        ];
    }

    connectedCallback() {
        this.render();
        this.attachEventListeners();
        this.loadLanguageSettings();
    }

    render() {
        const currentLang = this.availableLanguages.find(lang => lang.code === this.currentLanguage);
        
        this.innerHTML = `
            <div class="blog-language-switcher">
                <div class="language-dropdown">
                    <button class="language-btn" type="button">
                        <span class="flag">${currentLang.flag}</span>
                        <span class="language-name">${currentLang.name}</span>
                        <i class="fas fa-chevron-down"></i>
                    </button>
                    <div class="language-menu">
                        ${this.availableLanguages.map(lang => `
                            <div class="language-item ${lang.code === this.currentLanguage ? 'active' : ''}" 
                                 data-lang="${lang.code}">
                                <span class="flag">${lang.flag}</span>
                                <span class="language-name">${lang.name}</span>
                                ${lang.code === this.currentLanguage ? '<i class="fas fa-check"></i>' : ''}
                            </div>
                        `).join('')}
                    </div>
                </div>
            </div>
        `;
    }

    attachEventListeners() {
        const btn = this.querySelector('.language-btn');
        const menu = this.querySelector('.language-menu');
        const items = this.querySelectorAll('.language-item');

        btn.addEventListener('click', () => {
            menu.classList.toggle('show');
        });

        items.forEach(item => {
            item.addEventListener('click', () => {
                const langCode = item.dataset.lang;
                this.switchLanguage(langCode);
                menu.classList.remove('show');
            });
        });

        // 点击外部关闭菜单
        document.addEventListener('click', (e) => {
            if (!this.contains(e.target)) {
                menu.classList.remove('show');
            }
        });
    }

    async switchLanguage(langCode) {
        if (langCode === this.currentLanguage) return;

        try {
            // 调用API切换语言
            const response = await fetch('/api/i18n/set-language', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ language: langCode })
            });

            if (response.ok) {
                this.currentLanguage = langCode;
                this.render();
                this.saveLanguageSettings();
                
                // 触发语言切换事件
                this.dispatchEvent(new CustomEvent('languageChanged', {
                    detail: { language: langCode }
                }));

                // 重新加载页面内容
                this.reloadContent();
            }
        } catch (error) {
            console.error('切换语言失败:', error);
        }
    }

    loadLanguageSettings() {
        const savedLang = localStorage.getItem('blog-language') || 'zh-CN';
        this.currentLanguage = savedLang;
        this.render();
    }

    saveLanguageSettings() {
        localStorage.setItem('blog-language', this.currentLanguage);
    }

    reloadContent() {
        // 重新加载博客内容
        if (typeof BlogManager !== 'undefined') {
            BlogManager.refreshContent();
        }
    }

    // 获取当前语言
    getCurrentLanguage() {
        return this.currentLanguage;
    }

    // 获取可用语言列表
    getAvailableLanguages() {
        return this.availableLanguages;
    }
}

// 注册自定义元素
customElements.define('blog-language-switcher', BlogLanguageSwitcher);